Page({
  data: {
    showPopup: false,
    selectedLevel: '',
    selectedAmount: 0,
    membershipLevels: {
      silver: {
        name: '银卡会员',
        price: 365,
        desc: '基础会员权益'
      },
      black: {
        name: '黑卡会员',
        price: 668,
        desc: '尊享会员权益'
      },
      platinum: {
        name: '铂金会员',
        price: 1288,
        desc: '至尊会员权益'
      }
    }
  },

  onLoad() {
    // 页面加载时的初始化逻辑
  },

  // 显示充值弹窗
  showRechargePopup() {
    this.setData({
      showPopup: true
    });
  },

  // 隐藏充值弹窗
  hideRechargePopup() {
    this.setData({
      showPopup: false,
      selectedLevel: '',
      selectedAmount: 0
    });
  },

  // 阻止冒泡
  stopPropagation() {
    return;
  },

  // 选择会员等级
  selectLevel(e) {
    const level = e.currentTarget.dataset.level;
    const amount = this.data.membershipLevels[level].price;
    
    this.setData({
      selectedLevel: level,
      selectedAmount: amount
    });
  },

  // 会员充值
  toMemberRecharge() {
    wx.navigateTo({
      url: '/page/memberrecharge/index',
    })
  },

  // 处理支付
  handlePayment() {
    if (!this.data.selectedLevel) {
      wx.showToast({
        title: '请选择会员等级',
        icon: 'none'
      });
      return;
    }

    const selectedLevel = this.data.membershipLevels[this.data.selectedLevel];

    // 调用微信支付
    wx.requestPayment({
      timeStamp: '',  // 支付签名时间戳
      nonceStr: '',   // 随机字符串
      package: '',    // 统一下单接口返回的 prepay_id 参数值
      signType: 'MD5',
      paySign: '',    // 支付签名
      success: (res) => {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            // 支付成功后的处理逻辑
            setTimeout(() => {
              this.hideRechargePopup();
              // 刷新会员信息
              this.updateMemberInfo();
            }, 2000);
          }
        });
      },
      fail: (err) => {
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        });
      }
    });
  },

  // 更新会员信息
  updateMemberInfo() {
    // 调用后端接口更新会员信息
    wx.request({
      url: 'YOUR_API_URL/updateMember',
      method: 'POST',
      data: {
        level: this.data.selectedLevel,
        amount: this.data.selectedAmount
      },
      success: (res) => {
        // 处理成功响应
      },
      fail: (err) => {
        // 处理错误
        wx.showToast({
          title: '更新会员信息失败',
          icon: 'none'
        });
      }
    });
  }
}); 